package com.hoo.service.account;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.hoo.common.constant.Constant;
import com.hoo.entity.account.District;
import com.hoo.entity.account.SearchVisitorResult;
import com.hoo.entity.account.Visitor;
import com.hoo.form.account.SearchForm;
import com.hoo.form.account.VisitorForm;
import com.hoo.form.order.TicketOrderForm;
import com.hoo.mapper.account.VisitorMapper;
import com.hoo.service.order.TicketOrderService;
import com.hoo.util.DateUtils;
import com.hoo.util.PaginationSupport;
import com.hoo.util.Utils;

@Service
public class VisitorService {

	@Autowired
	VisitorMapper visitorMapper;
	
	@Autowired
	TicketOrderService ticketOrderService;
	
	//TicketOrderService ticketOrderService = new TicketOrderService();
	
	
	public List<SearchVisitorResult> getVisitorInEveProviceBetweenTime(SearchForm form){
		return this.visitorMapper.getVisitorInEveProviceBetweenTime(form);
	}
	
	
	
	/**
	 * 查询各年龄段的游客，并拼接成json格式：[{name:"",data:[]}],为前台报表显示提供所需格式数据
	 * @return
	 */
	public List<Map<String, Object>> getVisitorGroupMapYear() {
		int visitorGroupArr[] = null;
		int count = 0;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 3; i++) {
			Map<String, Object> tempMap = new HashMap<String, Object>();
			List<Map<String, Object>> tempList = visitorMapper.getVisitorGroupMapYear(i);
			visitorGroupArr = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
			count = 0;
			for (Map<String, Object> map : tempList) {
				int index = Integer.valueOf((String) map.get("type")).intValue();
				visitorGroupArr[index] = Integer.parseInt(String.valueOf(map.get("total")));
				count += Integer.parseInt(String.valueOf(map.get("total")));
			}
			visitorGroupArr[7] = count;
			tempMap.put("name", new Date().getYear() + 1900 - i);
			tempMap.put("data", visitorGroupArr);
			list.add(tempMap);
		}
		return list;
	}
	public List<Map<String, Object>> getVisitorGroupMapDay(SearchForm form) {
		int visitorGroupArr[] = null;
		int count = 0;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> tempMap = new HashMap<String, Object>();
		List<Map<String, Object>> tempList = visitorMapper.getVisitorGroupMapDay(form);
		visitorGroupArr = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
		count = 0;
		for (Map<String, Object> map : tempList) {
			int index = Integer.valueOf((String) map.get("type")).intValue();
			visitorGroupArr[index] = Integer.parseInt(String.valueOf(map.get("total")));
			count += Integer.parseInt(String.valueOf(map.get("total")));
		}
		visitorGroupArr[7] = count;
		tempMap.put("name", new Date().getYear() + 1900);
		tempMap.put("data", visitorGroupArr);
		list.add(tempMap);
		return list;
	}

	/**
	 * 网络购票,添加游客信息，添加票务信息
	 * @param form
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
	public String insertVisitorHanderOnline(TicketOrderForm form) {
		//返回预约号
		Map<String, String> map = this.ticketOrderService.insertTicketOrderHanderOnline(form);
		if(map==null){
			return null;
		}
		if( map.get("scheduleNum") =="" || map.get("scheduleNum") == null){
			return null;
		}
		Visitor visitor = new Visitor();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				Constant.DATE_FORMAT_LONG_ONE);
		for (int i = 0; i < form.getList().size(); i++) {
			visitor = new Visitor();
			visitor.setIdentityCard(form.getList().get(i).getIdentityCard());
			visitor.setName(form.getList().get(i).getName());
			visitor.setNationId(1);//网络购票时，游客民族默认为汉族
			visitor.setLinkmanID(form.getLinkmanID());
			try {
				visitor.setAge(DateUtils.getAge(new Date(new StringBuffer(form.getList().get(i).getIdentityCard().substring(6,14)).insert(4, '/').insert(7,'/').toString())));
				visitor.setBirthday(simpleDateFormat.parse(simpleDateFormat
						.format(new Date(new StringBuffer(form.getList().get(i).getIdentityCard().substring(6,14)).insert(4, '/').insert(7,'/').toString()))));
			} catch (Exception e) {
				e.printStackTrace();
			}
			visitor.setInternetTrading(1);//1:网络购票，2：现场购票
			visitor.setGroupTicket(form.getGroupTicket());//1：团队票，2：散票
			visitor.setCertificateType(form.getCertificateType());
			//根据游客身份证号查询所在省市
			District district = this.visitorMapper.getDistrictByCityCode(this.cutCondition(form.getList().get(i).getIdentityCard()));
			visitor.setAddress(district.getProviceDisplay()+district.getCityDisplay());
			visitor.setDistrictCode(this.cutCondition(form.getList().get(i).getIdentityCard()));
			visitor.setProviceCode(district.getId());
			visitor.setOrderNo(map.get("orderNo"));//将生成的订单号放到游客信息中，以便报表查询
			if(this.visitorMapper.insertVisitor(visitor)!=1){
				return null;
			}
		}
		return map.get("scheduleNum");
	}
	
	//@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
	public String handleInsertVisitorEvent(String visitorInfo) throws Exception{
			//检查当前是否有可有ticket
			if(null == Constant.ticketNo || "" == Constant.ticketNo){
				throw new Exception();
			}
		
			//SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constant.DATE_FORMAT_LONG_ONE);
			Map<String, Object> map = Utils.parseJSON2Map(visitorInfo);//visitorinfo为取票终端传来的游客身份信息
			if(ticketOrderService.getTicketOnUse().getResidueNum()<=0){
				return Constant.NO_REPERTORY;	//如馆人数已达上限
			}
			
			this.visitorMapper.getVisitorLatelyInvoteTicketTimeByIdCard(map.get("identityCard").toString());
			this.ticketOrderService.updateTicketResidueNum(Constant.ticketNo);   //修改剩余票数
			//插入订单
			String orderNo= this.ticketOrderService.insertTicketOrder(map);
			this.insertVisitor(map, orderNo);
			return Constant.SUCCESS;
	}
	
	
	/**
	 * 现场身份证取票，添加游客信息，添加票务信息
	 * @param visitorInfo
	 * @return
	 * @throws Exception
	 */
	
	public int insertVisitor(Map<String, Object> map,String orderNo) throws Exception {
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constant.DATE_FORMAT_LONG_ONE);
			Visitor visitor = new Visitor();
			visitor.setName(map.get("name").toString());
			visitor.setAge(DateUtils.getAge(new Date(map.get("birthday").toString())));
			visitor.setGender(Integer.parseInt(map.get("gender").toString()));
			visitor.setCertificateType(1);
			visitor.setInternetTrading(2);//1:网络购票，2：现场购票
			visitor.setGroupTicket(2); //1：团队票，2：散票
			visitor.setNationId(Integer.parseInt(map.get("nationId").toString()));
			visitor.setIdentityCard(map.get("identityCard").toString());
			visitor.setLinkmanID(map.get("identityCard").toString());
			visitor.setSignAndIssue(map.get("signAndIssue").toString());
			visitor.setDistrictCode(cutCondition(map.get("identityCard").toString()));
			
			visitor.setBirthday(simpleDateFormat.parse(simpleDateFormat
					.format(new Date(map.get("birthday").toString()))));
			visitor.setStartTime(simpleDateFormat.parse(simpleDateFormat
					.format(new Date(map.get("startTime").toString()))));
			visitor.setEndTime(simpleDateFormat.parse(simpleDateFormat
					.format(new Date(map.get("endTime").toString()))));
			
			visitor.setProviceCode(Integer.parseInt(map.get("identityCard").toString().substring(0,2)));
			visitor.setOrderNo(orderNo);
			visitor.setAddress(map.get("address").toString());
			visitor.setInvoteTime(new Date());
			
			return visitorMapper.insertVisitor(visitor);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}
	
	
	
	/*@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
	public int insertVisitor(String visitorInfo) throws Exception {
		try {
			//检查当前是否有可有ticket
			if(null == Constant.ticketNo || "" == Constant.ticketNo){
				return -1;
			}
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constant.DATE_FORMAT_LONG_ONE);
			Map<String, Object> map = Utils.parseJSON2Map(visitorInfo);//visitorinfo为取票终端传来的游客身份信息
			//插入订单
			String orderNo= this.ticketOrderService.insertTicketOrder(map);
			this.ticketOrderService.updateTicketResidueNum(Constant.ticketNo);   //修改剩余票数
			
			Visitor visitor = new Visitor();
			visitor.setName(map.get("name").toString());
			visitor.setAge(DateUtils.getAge(new Date(map.get("birthday").toString())));
			visitor.setGender(Integer.parseInt(map.get("gender").toString()));
			visitor.setCertificateType(1);
			visitor.setInternetTrading(2);//1:网络购票，2：现场购票
			visitor.setGroupTicket(2); //1：团队票，2：散票
			visitor.setNationId(Integer.parseInt(map.get("nationId").toString()));
			visitor.setIdentityCard(map.get("identityCard").toString());
			visitor.setLinkmanID(map.get("identityCard").toString());
			visitor.setSignAndIssue(map.get("signAndIssue").toString());
			visitor.setDistrictCode(cutCondition(map.get("identityCard").toString()));
			
			visitor.setBirthday(simpleDateFormat.parse(simpleDateFormat
					.format(new Date(map.get("birthday").toString()))));
			visitor.setStartTime(simpleDateFormat.parse(simpleDateFormat
					.format(new Date(map.get("startTime").toString()))));
			visitor.setEndTime(simpleDateFormat.parse(simpleDateFormat
					.format(new Date(map.get("endTime").toString()))));
			
			visitor.setProviceCode(Integer.parseInt(map.get("identityCard").toString().substring(0,2)));
			visitor.setOrderNo(orderNo);
			visitor.setAddress(map.get("address").toString());
			visitor.setInvoteTime(new Date());
			return this.visitorMapper.insertVisitor(visitor);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}
*/
	/**
	 * 根据市级省市编号的不同，从身份证号上截取相应的长度
	 * 
	 * @param ID
	 * @return
	 */
	private int cutCondition(String ID) {
		String result = "";
		if ((Integer.parseInt(String.valueOf(ID.charAt(2))) == 9)
				|| (ID.substring(0, 4) == "4600")
				|| (ID.substring(0, 4) == "4421")
				|| (ID.substring(0, 2) == "11") || (ID.substring(0, 2) == "12")
				|| (ID.substring(0, 2) == "31") || (ID.substring(0, 2) == "50")) {
			result = ID.substring(0, 6);
		} else {
			result = ID.substring(0, 4);
		}
		return Integer.parseInt(result);
	}

	
	// 查询各个省份的游客数
	public List<SearchVisitorResult> getVisitorInEveProvice() {
		return this.visitorMapper.getVisitorInEveProvice();
	}

	// 查询指定省份下各个市的游客数
	public List<SearchVisitorResult> getVisitorCityResults(SearchForm form) {
		return this.visitorMapper.getVisitorInEveCity(form);
	}

	/*public List<Visitor> getVisitor(VisitorForm form) {
		return this.visitorMapper.getVisitor(form);
	}*/

	/**
	 * 获取所有省份
	 * @return
	 */
	public List<District> getAllProvices() {
		return this.visitorMapper.getAllProvices();
	}

	/**
	 * 查询统计最近三十分钟内游客信息，用于hightchart
	 * @return
	 */
	public List<SearchVisitorResult> statisticsVisitorInThirtyMin() {
		return this.visitorMapper.statisticsVisitorInThirtyMin();
	}
	
	/**
	 * 查询一天中每个小时的游客数,用于hightchart
	 * @param map
	 * @return
	 */
	public List<SearchVisitorResult> getVisitorInDay(SearchForm form) {
		return this.visitorMapper.getVisitorInDay(form);
	}
	
	
	/**
	 * 查询指定是间内每个民族的人数,用于hightchart
	 * @param map
	 * @return
	 */
	public List<SearchVisitorResult> statisticsEveNationVisitor(SearchForm form) {
		List<SearchVisitorResult> list=this.visitorMapper.statisticsEveNationVisitor(form);
		int count=0;
		for (int i=0;i<37;i++) {
			count += list.get(19).getStaCount();
			list.remove(19);
		}
		SearchVisitorResult searchVisitorResult=new SearchVisitorResult();
		searchVisitorResult.setStaName("其他");
		searchVisitorResult.setStaCount(count);
		list.add(searchVisitorResult);
		return list;
	}
	/**
	 * 获取最近的游客信息
	 * @param map
	 * @return
	 */
	public List<SearchVisitorResult> getRecentVisitor(SearchForm form){
		return this.visitorMapper.getRecentVisitor(form);
	}
	
	/**
	 * 查询统计指定时间段内游客总数，团队总数，网络预约总数
	 * @param map
	 * @return
	 */
	public SearchVisitorResult statisticsPercent(SearchForm form){
		return this.visitorMapper.statisticsPercent(form);
	}
	private List<SearchVisitorResult> setList(List<SearchVisitorResult> list){
		DecimalFormat decimalFormat=new DecimalFormat("0.00");
		for(SearchVisitorResult visitor:list){
			visitor.setScatteredCount(visitor.getStaCount()-visitor.getStaGroupCount());
			if(visitor.getStaCount()==0){
				visitor.setGroupPrecent("0.00%");
				visitor.setMeshPrecent("0.00%");
				visitor.setScatteredPrecent("0.00%");
			}else {
				visitor.setGroupPrecent(decimalFormat.format(((float)visitor.getStaGroupCount()/visitor.getStaCount())*100)+"%");
				visitor.setMeshPrecent(decimalFormat.format(((float)visitor.getStaInternetTradingCount()/visitor.getStaCount())*100)+"%");
				visitor.setScatteredPrecent(decimalFormat.format((1-(float)visitor.getStaGroupCount()/visitor.getStaCount())*100)+"%");
			}
			visitor.setScatteredCount(visitor.getStaCount()-visitor.getStaGroupCount());
		}
		return list;
	}
	public PaginationSupport<SearchVisitorResult> getVisitorInfoInDay(SearchForm form) {
		List<SearchVisitorResult> list = this.visitorMapper.getVisitorInfoInDay(form);
		return new PaginationSupport(setList(list), 11,10,0);
	}

	public PaginationSupport<SearchVisitorResult> getVisitorInfoRecent(SearchForm form) {
		List<SearchVisitorResult> list = this.visitorMapper.getVisitorInfoRecent(form);
		return new PaginationSupport(setList(list), 8,10,0);
	}
	
	/**
	 * 最近三十分钟内游客信息表，用于dateTable
	 * @param form
	 * @return
	 */
	public PaginationSupport<Visitor> getVisitorInThirtyMin(VisitorForm form) {
		int totalCount = this.visitorMapper.getVisitorCount(form);
		List<Visitor> list = this.visitorMapper.getVisitorList(form);
		return new PaginationSupport(list, totalCount,form.getiDisplayLength(), form.getiDisplayStart());
	}
	
	public PaginationSupport<SearchVisitorResult> statisticsEveProviceVisitorInf(SearchForm form) {
		List<SearchVisitorResult> list = this.visitorMapper.statisticsEveProviceVisitorInf(form);
		return new PaginationSupport(setList(list), 34,34,0);
	}
	
	/**
	 * @return  按照地图的设定，对这些省市进行设值
	 */
	public String  mkData(){
		StringBuffer sb = new StringBuffer("");
		Map<String,String> myMap= new HashMap<String,String>(40);
		myMap.put("吉林省","cn-jl");        
		myMap.put("天津市","cn-tj");        
		myMap.put("安徽省","cn-ah");        
		myMap.put("山东省","cn-sd");        
		myMap.put("山西省","cn-sx");        
		myMap.put("新疆维吾尔自治区","cn-xj");
		myMap.put("河北省","cn-hb");        
		myMap.put("河南省","cn-he");        
		myMap.put("湖南省","cn-hn");        
		myMap.put("甘肃省","cn-gs");        
		myMap.put("福建省","cn-fj");        
		myMap.put("贵州省","cn-gz");        
		myMap.put("重庆市","cn-cq");        
		myMap.put("江苏省","cn-js");        
		myMap.put("湖北省","cn-hu");        
		myMap.put("内蒙古自治区","cn-nm");  
		myMap.put("广西壮族自治区","cn-gx"); 
		myMap.put("黑龙江省","cn-hl");      
		myMap.put("云南省","cn-yn");        
		myMap.put("辽宁省","cn-ln");        
		myMap.put("香港特别行政区","cn-6668"); 
		myMap.put("浙江省","cn-zj");        
		myMap.put("上海市","cn-sh");        
		myMap.put("北京市","cn-bj");        
		myMap.put("广东省","cn-gd");        
		myMap.put("澳门特别行政区","cn-3681"); 
		myMap.put("西藏自治区","cn-xz");    
		myMap.put("陕西省","cn-sa");        
		myMap.put("四川省","cn-sc");        
		myMap.put("海南省","cn-ha");        
		myMap.put("宁夏回族自治区","cn-nx"); 
		myMap.put("青海省","cn-qh");        
		myMap.put("江西省","cn-jx");        
		myMap.put("台湾省","tw-tw");        
		//  {"hc-key": "cn-sh","value": 0},
		Map<String, String> mapList=new HashMap<String, String>();
		List<SearchVisitorResult> list = visitorMapper.getVisitorInEveProvice();
		for(int i=0;i<list.size();i++){
			mapList.put(list.get(i).getStaProviceDisplay(), String.valueOf(list.get(i).getStaCount()));
		}
		for (Object o : myMap.keySet()) { 
			sb.append("{'hc-key':'").
			append(myMap.get(o)).
			append("','value':").
			append(mapList.get(o)).
			append("},").append("\n");
		}
		return sb.deleteCharAt(sb.length()-2)+"";
	}

}
